<template>
    <eui-background type="common">
        <eui-nav-bar title="缺货拣货" color="#fff" />
        <view class="footer" :style="{ height: height + 'px' }" v-if="goodsList.length > 0">
            <view
                style="width: 100%; background: #FFE9DA;padding: 15rpx 20rpx 15rpx 15rpx;color:#FF0000;box-sizing: border-box;font-size: 32rpx;line-height: 45rpx;"
                class="flex just-between align-center">
                <view style="flex: 1;">提示：新商品与原商品价格不同时，差异金额会执行退款或转成折扣</view>
            </view>
            <view
                style="height: 65rpx;font-size: 32rpx;line-height: 65rpx;padding: 0 17rpx 0 10rpx;box-sizing: border-box;"
                class="flex align-center just-between">
                <view class="flex align-center">请选择调整商品 <view style="color: #4F97FF;margin-left: 10rpx"
                        class="bold flex align-center" @click="showInfoModal"><text>调整说明 </text><eui-uicons
                            type="help-filled" size="40" style="color: #4F97FF;"></eui-uicons></view>
                </view>
            </view>
            <scroll-view scroll-y="true" class="bg-white"
                style="width: 100%;padding: 10rpx;box-sizing: border-box;overflow-y: scroll;">
                <view>
                    <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
                        <checkbox-group @change="checkboxChange(index)">
                            <checkbox :value="item.orderGoodsId" :checked="item.checked" />
                        </checkbox-group>
                        <view
                            style="width: 40rpx;height: 40rpx;text-align: center;line-height: 40rpx;background-color: #D8D8D8;color: #fff;border-radius: 40rpx;font-size: 32rpx;">
                            {{ index + 1 }}
                        </view>
                        <view style="margin-left: 10rpx;box-sizing: border-box;flex: 1;">
                            <view class="goods-info">
                                <view class="flex just-between">
                                    <view class="goods-name bold" style="flex: 1;">{{ item.goodsName }}</view>
                                    <view style="color: #000;"
                                        class="flex align-center goods-quantity just-between bold">
                                        <view style="font-size: 36rpx;">x{{ item.goodsNum }}</view>
                                        <view style="margin-left: 25rpx">¥ {{
            (item.actualPrice * item.goodsNum).toFixed(2)
        }}</view>
                                    </view>
                                </view>
                                <view class="flex just-between">
                                    <view style="font-size: 32rpx;color: #626262;">
                                        {{ item.goodsCode }}-{{ item.goodsBarcode }}
                                    </view>
                                </view>
                                <view class="flex just-between">
                                    <view class="flex">
                                        <view class="goods-quantity" style="margin-right: 40rpx;font-size: 25rpx;">
                                            缺货<text
                                                style="font-weight: bold;color: #000;margin-left: 4rpx;font-size: 32rpx;">x{{
            item.soldOutGoodsNum }}</text></view>
                                        <view class="goods-quantity" style="margin-right: 40rpx;font-size: 25rpx;">
                                            换货<text
                                                style="font-weight: bold;color: #000;margin-left: 4rpx;font-size: 32rpx">x{{
            getExchangeNum(item) }}</text>
                                        </view>
                                        <view style="font-size: 25rpx;color: #626262;">应拣<text
                                                style="font-weight: bold;color: #000;margin-left: 4rpx;font-size: 32rpx">x{{
            getPickUpNum(item) }}</text></view>
                                    </view>
                                    <view style="color: #4F97FF;line-height: 33rpx;font-size: 32rpx" class="bold"
                                        @click="openContactCustPop(item, index)">增加调整商品
                                    </view>
                                </view>
                            </view>
                            <view v-show="item.checked">
                                <view v-for="(f, i) in item.refundGoodsList" :key="index + '_' + i">
                                    <view
                                        style="display: flex;justify-content: space-between;margin-top: 6rpx;font-size: 25rpx;color: #000;">
                                        <view class="flex align-center co-00">
                                            <view
                                                style="width: 72rpx; height: 28rpx; background: #D4F2FF; border-radius: 3rpx;text-align: center;line-height: 28rpx;color: #4B9BFF;font-size: 25rpx;padding:4rpx;margin-right: 6rpx;">
                                                换货{{ i + 1 }}</view>
                                        </view>
                                        <view style="font-size: 32rpx;margin-left: 6rpx;flex: 1;">

                                            <view class="flex bold just-between">
                                                <view style="color: #4F97FF;" @click="editApplyNum(index, i)">原商品数量x{{
            f.useExchangeGoodsQuantity }}
                                                </view>
                                                <view class="goods-quantity" style="color: #000;">{{
            formatPrice(item.actualPrice * f.useExchangeGoodsQuantity) }}
                                                </view>
                                            </view>
                                            <view class="goods-name bold">{{ f.goodsName }}</view>
                                            <view class="flex align-center">
                                                <view style="font-size: 32rpx;color: #626262;flex:1">
                                                    {{ f.goodsCode }}-{{ f.goodsBarcode }}
                                                </view>
                                                <view class="goods-quantity bold" style="color: #000;">{{
            formatPrice(f.storePrice * f.applyRefundNum) }}</view>
                                            </view>
                                            <view class="flex align-center"
                                                style="font-size: 32rpx;justify-content: flex-end;"
                                                v-if="f.isFreshGoods != '1'">
                                                <eui-uicons type="minus-filled" size="60"
                                                    :style="{ 'color': Number(f.applyRefundNum) == 0 ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                                    :data-value="f.applyRefundNum"
                                                    @click="minusNum(index, i)"></eui-uicons>
                                                <view style="color: #626262;width: 60rpx;" class="text-center">
                                                    {{ Number(f.applyRefundNum) }}</view>
                                                <eui-uicons type="plus-filled" size="60"
                                                    :style="{ 'color': '#85B6FD !important' }"
                                                    @click="plusNum(index, i)"></eui-uicons>
                                            </view>
                                            <view class='flex just-between' v-else>
                                                <view style="font-size: 32rpx;" class="flex align-center">
                                                    <view class="co-00">实拣</view>
                                                    <view
                                                        style="width: 203rpx;height: 52rpx;margin-left:6rpx;background-color: #F1F1F1;padding: 6rpx;box-sizing: border-box;"
                                                        class="flex">
                                                        <input placeholder="请输入"
                                                            placeholder-style="color:#959595;font-size: 32rpx;font-weight:initial;"
                                                            type="number" :value="f.applyRefundWeight"
                                                            :data-index="index" :data-i="i" @blur="handleInputWeight"
                                                            style="padding: 2rpx 0 2rpx 2rpx;font-weight: bold;" />
                                                        <text class="bold">g</text>
                                                    </view>
                                                </view>
                                                <view style="text-align: right;">
                                                    实拣
                                                    <text class="bold" style="margin-left: 20rpx;">x{{
            Number(f.applyRefundNum) }}</text>
                                                </view>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view style="padding: 10rpx 8rpx;">
                        <view style="font-size: 28rpx;margin-top: 6rpx" class="flex just-between bold">
                            <view>缺货</view>
                            <view>{{ sumRows('soldOutGoodsNum') }}行/{{ sumNum('soldOutGoodsNum') }}件</view>
                        </view>
                        <view style="font-size: 28rpx;" class="flex just-between bold">
                            <view>换货</view>
                            <view>{{ sumRows('useExchangeGoodsQuantity') }}行/{{ sumNum('useExchangeGoodsQuantity')
                                }}件</view>
                        </view>
                        <view style="font-size: 28rpx;" class="flex just-between bold">
                            <view>调整前后</view>
                            <view><text style="margin-right: 15rpx;">{{ goodsList.filter(a =>
            !!a.checked).length }}行/{{ sumNum('goodsNum') }}件</text><text
                                    style="color: #939393;">{{ '-->' }}</text><text style="margin-left: 15rpx;">{{
            sumKind() }}行/{{ getApplyRefundNum() }}件</text>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
        <view class="footer align-center" :style="{ height: height + 'px' }" v-else>
            <view class="m-list-template-image" style="flex: 1;margin-top: 25%;">
                <image :src="_img_blank_order" />
                <view style="color: #9e9e9e;font-size: 32rpx;text-align: center;">无可操作的商品</view>
            </view>
        </view>
        <view class="bottom" v-if="goodsList.length > 0">
            <eui-button title="确认提交" type="max" singleTag="confirm" @buttonClick="buttonClick"
                style="width: 100%;height: 86rpx;line-height: 86rpx;border-radius: 0;margin: 0;padding: 0;"
                :disabled="sumNum('soldOutGoodsNum') == 0 && sumNum('useExchangeGoodsQuantity') == 0" />
        </view>
        <eui-popup ref="popup" background-color="#fff" type="bottom" :mask-click="false">
            <view class="popup-content">
                <view class="popup-title flex just-between">
                    <view style="font-weight: bold;">
                        调整说明
                    </view>
                    <bcm-close-btn @click="close"></bcm-close-btn>
                </view>
                <scroll-view scroll-y="true"
                    style="padding: 8rpx 8rpx 8rpx 32rpx;box-sizing: border-box;height: 70vh;overflow-y: scroll;text-align: left;">
                    <view class="bold">缺货</view>
                    <view>
                        <view>1.普通商品仅支持按数量操作缺货，称重商品支持部分数量缺货；</view>
                        <view>2.缺货商品将转换成退款金额，退款给顾客；</view>
                    </view>
                    <view class="bold">换货</view>
                    <view>
                        <view>1.每一笔订单只允许操作一次换货；换货成功后会产生新的订单，原订单自动取消，请留意新订单；</view>
                        <view>2.低价商品换高价商品，系统会自动差异部分金额转成折扣；高价商品换低价商品，系统会自动执行差额退款；</view>
                        <view>3.换货新商品数量可与原商品数量不一致，普通商品仅支持按数量操作换货，支持称重商品部分数量换货；</view>
                        <view>4.存在部分退、退差或未审核的售后申请，则不支持换货操作；</view>
                        <!-- <view>5.预计退款金额仅供参考，请以实际退款金额为准。</view> -->
                    </view>
                </scroll-view>
                <view class="bottom-1">
                    <eui-button type="max2" title="关闭" style="width: 50%;" singleTag="close"
                        @buttonClick="buttonClick" />
                </view>
            </view>
        </eui-popup>
        <eui-popup ref="addExchangeInfoPopup" type="bottom" :animation="false" background-color="#fff"
            :mask-click="false">
            <view class="popup-content" v-if="!!goodsList[currentItemIndex]" style="height: 40vh;">
                <view class="popup-title flex just-between">
                    <view style="font-weight: bold;">
                        请选择调整类型<text v-show="!!currentItem.orderGoodsRow">(第{{ currentItem.orderGoodsRow
                            }}行)</text>
                    </view>
                    <bcm-close-btn @click="closeContactCustPopup"></bcm-close-btn>
                </view>
                <view
                    style="padding-left: 32rpx;color: #000;background-color:#fff;box-sizing: border-box;padding-top:24rpx;text-align: left;height: 50vh;">
                    <view class="flex">
                        <view style="margin-right: 30rpx;width: 180rpx;text-align: right;">调整类型 </view>
                        <radio-group @change="radioChange">
                            <radio value="0" :checked="exchangeType === '0'">缺货</radio>
                            <radio value="1" :checked="exchangeType === '1'" style="margin-left: 30rpx;">换货
                            </radio>
                        </radio-group>
                    </view>
                    <view class="flex align-center" v-if="currentItem.isFreshGoods == '0'" style="height: 90rpx;">
                        <view style="margin-right: 30rpx;width: 180rpx;text-align: right;">{{ exchangeType ==
            '0' ? '缺货数量' : '原商品数量' }}</view>
                        <view class="flex align-center" style="font-size: 32rpx;justify-content: flex-end;"
                            v-if="exchangeType == '0'">
                            <eui-uicons type="minus-filled" size="60"
                                :style="{ 'color': currentItem.soldOutGoodsNum == 0 ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                @click="minusExchangeNum()"></eui-uicons>
                            <view style="color: #626262;width: 180rpx;" class="text-center">{{
            currentItem.soldOutGoodsNum }}</view>
                            <eui-uicons type="plus-filled" size="60"
                                :style="{ 'color': getRestExchangeNum(goodsList[currentItemIndex]) == currentItem.soldOutGoodsNum ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                @click="plusExchangeNum()"></eui-uicons>
                        </view>
                        <view class="flex align-center" style="font-size: 32rpx;justify-content: flex-end;" v-else>
                            <eui-uicons type="minus-filled" size="60"
                                :style="{ 'color': currentItem.useExchangeGoodsQuantity <= 1 ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                @click="minusExchangeNum()"></eui-uicons>
                            <view style="color: #626262;width: 180rpx;" class="text-center">{{
            currentItem.useExchangeGoodsQuantity }}</view>
                            <eui-uicons type="plus-filled" size="60"
                                :style="{ 'color': getPickUpNum(goodsList[currentItemIndex]) == currentItem.useExchangeGoodsQuantity ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                @click="plusExchangeNum()"></eui-uicons>
                        </view>
                    </view>
                    <view style="height: 90rpx;" v-else>
                        <view v-if="exchangeType == '1'" class="flex  align-center">
                            <view style="margin-right: 30rpx;width: 180rpx;text-align: right;">
                                原商品数量</view>
                            <view class="flex align-center" style="font-size: 32rpx;justify-content: flex-end;">
                                <eui-uicons type="minus-filled" size="60"
                                    :style="{ 'color': currentItem.soldOutGoodsNum == 1 ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                    @click="minusExchangeNum()"></eui-uicons>
                                <view style="color: #626262;width: 180rpx;" class="text-center">{{
            Number(currentItem.soldOutGoodsNum) }}</view>
                                <eui-uicons type="plus-filled" size="60"
                                    :style="{ 'color': getPickUpNum(goodsList[currentItemIndex]) == currentItem.soldOutGoodsNum ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                    @click="plusExchangeNum()"></eui-uicons>
                            </view>
                        </view>
                        <view style="font-size: 32rpx;" v-else>
                            <view class="flex align-center" style="height: 60rpx;">
                                <view style="margin-right: 30rpx;width: 180rpx;text-align: right">应拣数量</view>
                                <view>{{ getRestExchangeNum(goodsList[currentItemIndex]) }}</view>
                            </view>
                            <view class="flex align-center" style="height: 60rpx;">
                                <view style="margin-right: 30rpx;width: 180rpx;text-align: right">应拣重量</view>
                                <view>{{
            (currentItem.soldOutWeight) }}g
                                </view>
                            </view>
                            <view class="flex align-center" style="height: 60rpx;">
                                <view class="co-00" style="margin-right: 30rpx;width: 180rpx;text-align: right;">实拣重量
                                </view>
                                <view
                                    style="width: 203rpx;height: 52rpx;margin-left:6rpx;background-color: #F1F1F1;padding: 6rpx;box-sizing: border-box;"
                                    class="flex">
                                    <input placeholder="请输入"
                                        placeholder-style="color:#959595;font-size: 32rpx;font-weight:initial;"
                                        :value="currentItem.applyRefundWeight" @blur="handleInputCurrentWeight"
                                        type="number" style="padding: 2rpx 0 2rpx 2rpx;font-weight: bold;" />
                                    <text class="bold">g</text>
                                </view>
                            </view>
                            <view class="flex align-center" style="height: 60rpx;">
                                <view style="margin-right: 30rpx;width: 180rpx;text-align: right;">缺货数量</view>
                                <view>{{ Number(currentItem.soldOutGoodsNum) }}</view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="bottom-1">
                    <eui-button type="max2" title="取消" style="width: 40%" singleTag="cancel"
                        @buttonClick="buttonClick" />
                    <eui-button type="max" title="确定" style="width: 40%" singleTag="confirmexchange"
                        @buttonClick="buttonClick" />
                </view>
            </view>
        </eui-popup>
        <eui-popup ref="editExchangeInfoPopup" type="bottom" :animation="false" background-color="#fff"
            :mask-click="false"
            v-if="(currentItem.refundGoodsList) && (currentItem.refundGoodsList.length) && (!!exchangeGoodsIndex || exchangeGoodsIndex == 0)">
            <view class="popup-content">
                <view class="popup-title flex just-between">
                    <view style="font-weight: bold;">
                        修改换货信息<text v-show="!!currentItem.orderGoodsRow">(第{{ currentItem.orderGoodsRow
                            }}行-换货{{ exchangeGoodsIndex + 1 }})</text>
                    </view>
                    <bcm-close-btn @click="closeEditExchangeInfoPopup"></bcm-close-btn>
                </view>
                <view
                    style="padding-left: 32rpx;color: #000;background-color:#fff;box-sizing: border-box;padding-top:24rpx;text-align: left">
                    <view v-if="currentItem.isFreshGoods == '0'">
                        <view class="flex align-center" style="height: 90rpx;">
                            <view style="margin-right: 30rpx;width: 180rpx;text-align: right;">原商品数量</view>
                            <view class="flex align-center" style="font-size: 32rpx;justify-content: flex-end;">
                                <eui-uicons type="minus-filled" size="60"
                                    :style="{ 'color': ((exchangeGoodsItem.useExchangeGoodsQuantity == 0)) ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                    @click="minusExchangeNum('edit')"></eui-uicons>
                                <view style="color: #626262;width: 180rpx;" class="text-center">
                                    {{ exchangeGoodsItem.useExchangeGoodsQuantity }}</view>
                                <eui-uicons type="plus-filled" size="60"
                                    :style="{ 'color': goodsList[currentItemIndex].refundGoodsList[exchangeGoodsIndex].useExchangeGoodsQuantity <= exchangeGoodsItem.useExchangeGoodsQuantity ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                    @click="plusExchangeNum('edit')"></eui-uicons>
                            </view>
                        </view>
                        <view class="flex align-center" style="height: 90rpx;">
                            <view style="margin-right: 30rpx;width: 180rpx;text-align: right;">新商品数量</view>
                            <view class="flex align-center" style="font-size: 32rpx;justify-content: flex-end;">
                                <eui-uicons type="minus-filled" size="60"
                                    :style="{ 'color': exchangeGoodsItem.applyRefundNum == 0 ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                    @click="minusExchangeNumNormal()"></eui-uicons>
                                <view style="color: #626262;width: 180rpx;" class="text-center">{{
            Number(exchangeGoodsItem.applyRefundNum) }}</view>
                                <eui-uicons type="plus-filled" size="60" :style="{ 'color': '#85B6FD !important' }"
                                    @click="plusExchangeNumNormal()"></eui-uicons>
                            </view>
                        </view>
                    </view>
                    <view v-else>
                        <view class='flex align-center' style="height: 90rpx;">
                            <view style="margin-right: 30rpx;width: 180rpx;text-align: right;">原商品数量</view>
                            <view class="flex align-center" style="font-size: 32rpx;justify-content: flex-end;">
                                <eui-uicons type="minus-filled" size="60"
                                    :style="{ 'color': ((exchangeGoodsItem.useExchangeGoodsQuantity == 0)) ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                    @click="minusExchangeNum('edit')"></eui-uicons>
                                <view style="color: #626262;width: 180rpx;" class="text-center">
                                    {{ exchangeGoodsItem.useExchangeGoodsQuantity }}</view>
                                <eui-uicons type="plus-filled" size="60"
                                    :style="{ 'color': currentItem.refundGoodsList[exchangeGoodsIndex].useExchangeGoodsQuantity <= exchangeGoodsItem.useExchangeGoodsQuantity ? '#D8D8D8 !important' : '#85B6FD !important' }"
                                    @click="plusExchangeNum('edit')"></eui-uicons>
                            </view>
                        </view>
                        <view style="font-size: 32rpx;">
                            <view class="flex align-center">
                                <view style="margin-right: 30rpx;width: 180rpx;text-align: right">原商品重量</view>
                                <view>{{
                                    (currentItem.goodsWeight * 1000) }}g
                                </view>
                            </view>
                            <view class="flex align-center">
                                <view class="co-00" style="margin-right: 30rpx;width: 180rpx;text-align: right;">实拣重量
                                </view>
                                <view
                                    style="width: 203rpx;height: 52rpx;margin-left:6rpx;background-color: #F1F1F1;padding: 6rpx;box-sizing: border-box;"
                                    class="flex">
                                    <input placeholder="请输入"
                                        placeholder-style="color:#959595;font-size: 32rpx;font-weight:initial;"
                                        :value="exchangeGoodsItem.applyRefundWeight"
                                        @blur="handleInputEditCurrentWeight" type="number"
                                        style="padding: 2rpx 0 2rpx 2rpx;font-weight: bold;" />
                                    <text class="bold">g</text>
                                </view>
                            </view>
                            <view class="flex align-center">
                                <view style="margin-right: 30rpx;width: 180rpx;text-align: right;">新商品数量</view>
                                <view>{{ Number(exchangeGoodsItem.applyRefundNum) }}</view>
                            </view>
                        </view>
                    </view>
                    <view class="bottom-1" style="margin: 100rpx 0 50rpx 0;">
                        <eui-button type="max2" title="取消" style="width: 40%" singleTag="editCancel"
                            @buttonClick="buttonClick" />
                        <eui-button type="max" title="确定" style="width: 40%" singleTag="confirmexchangeEdit"
                            @buttonClick="buttonClick" />
                    </view>
                </view>
            </view>
        </eui-popup>
    </eui-background>
</template>
<script setup lang="js">
import { mapState, mapMutations } from 'vuex';
import { ref, computed, onMounted } from 'vue'
import { onLoad } from "@dcloudio/uni-app";
import service from '../../../common/service';
import { bcmRequest, getBcmUrl } from '../../../hooks/bcmServices';
import { makePhoneCall, getBcmDictName, getBcmDictItem, formatPrice } from '../../../hooks/bcmUseUntils';
import _img_blank_order from '../../../static/img/status/blank_order.png'
import BcmCloseBtn from '../components/BcmCloseBtn.vue';

const bcmUrl = getBcmUrl()

const goodsList = ref([])
const orderId = ref('')
const height = ref(0);
const bcmOrder  = ref(null)
const exchangeType = ref('0')
const currentItem  = ref({
    soldOutGoodsNum: 0,
    soldOutWeight: 0,
    returnGoodsList: [],
    useExchangeGoodsQuantity: 0,
    orderGoodsRow: 0,
    applyRefundWeight: 0
})
const currentItemIndex = ref(-2)
const exchangeGoodsIndex = ref(-2)
const exchangeGoodsItem= ref({
    useExchangeGoodsQuantity: 0,
    applyRefundNum: 0,
    applyRefundWeight: 0,
    isFreshGoods: '0',
    weight: ''
})
const editExchangeInfoPopup = ref(null)
const addExchangeInfoPopup = ref(null)
const popup = ref(null)

onMounted(() => {
    uni.getSystemInfo({
        success: function (res) { // res - 各种参数
            let info = uni.createSelectorQuery().select(".navigation");
            info.boundingClientRect(function (data) { //data - 各种参数
                height.value = res.windowHeight - data.height - 100;
            }).exec()
        }
    });
})

onLoad((option) => {
    if (option.orderId) {
        orderId.value = option.orderId;
        billQuery(option.orderId);
    }
})

const editApplyNum = (index, i) => {
    currentItem.value = { ...goodsList.value[index] }, currentItemIndex.value = index, exchangeGoodsItem.value = { ...goodsList.value[index].refundGoodsList[i] }, exchangeGoodsIndex.value = i;
    console.log(exchangeGoodsItem.value, goodsList.value[index].refundGoodsList[i])
    setTimeout(() => {
        openEditExchangeInfoPopup()
    }, 0)
}
const getRestExchangeNum = (item) => {
    return Number(item.goodsNum - getExchangeNum(item))
}
const handleInputWeight = (evt) => {
    const { value } = evt.detail, { dataset } = evt.target;
    let list = [...goodsList.value], item = list[dataset.index], i = dataset.i;
    item.refundGoodsList[i].applyRefundWeight = Number(value);
    if ((!Number.isInteger(Number(value))) || !value || Number(value) <= 0) {
        goodsList.value = list;
        uni.showToast({
            icon: 'none',
            title: '请输入大于0的整数'
        })

        setTimeout(() => {
            let remarkData = { ...item }
            // console.log(item,'itemitemitemitemitemitem')
            remarkData.refundGoodsList[i].applyRefundWeight = remarkData.refundGoodsList[i].weight * remarkData.refundGoodsList[i].applyRefundNum;
            // $set(goodsList, dataset.index, remarkData)
        }, 100)
        return
    }
    let perWeight = item.refundGoodsList[i].weight;
    // item.refundGoodsList[i].applyRefundWeight = Number(value);
    item.refundGoodsList[i].applyRefundNum = Number((value / perWeight).toFixed(3))
    goodsList.value = list;

}

const handleInputCurrentWeight = (evt) => {
    let total = currentItem.value.soldOutWeight, weight = Number(evt.detail.value), perWeight = total / getRestExchangeNum(goodsList.value[currentItemIndex.value]);
    currentItem.value.applyRefundWeight = weight;
    if (!Number.isInteger(weight) || weight < 0) {
        uni.showToast({
            icon: 'none',
            title: "请输入大于或者等于0的整数"
        })
        currentItem.value.applyRefundWeight = 0;
        currentItem.value.soldOutGoodsNum = 1;
        return
    }
    if ((!!weight || weight == 0) && total - weight >= 0) {
        currentItem.value.applyRefundWeight = weight;
        currentItem.value.soldOutGoodsNum = Number(((total - weight) / perWeight).toFixed(3))
    }
    if (total - weight < 0) {
        uni.showToast({
            icon: 'none',
            title: "实拣重量不可大于或等于原商品重量"
        })
        currentItem.value.applyRefundWeight = 0;
        currentItem.value.soldOutGoodsNum = 1
    }
}
const handleInputEditCurrentWeight = (evt) => {
    let weight = Number(evt.detail.value);
    exchangeGoodsItem.value.applyRefundWeight = weight;
    if (!Number.isInteger(weight) || weight < 0) {
        uni.showToast({
            icon: 'none',
            title: "请输入大于或者等于0的整数"
        })
        return
    }
    if ((!!weight || weight == 0)) {
        exchangeGoodsItem.value.applyRefundWeight = weight;
        exchangeGoodsItem.value.applyRefundNum = Number(((weight) / exchangeGoodsItem.value.weight).toFixed(3))
    }
}

const showInfoModal = () => {
    popup.value.open('center')
}

const radioChange = (evt) => {
    exchangeType.value = evt.detail.value;
    if (evt.detail.value == '1') {
        currentItem.value.useExchangeGoodsQuantity = getPickUpNum(goodsList.value[currentItemIndex.value])
    } else {
        currentItem.value.soldOutGoodsNum = getRestExchangeNum(goodsList.value[currentItemIndex.value])
    }
}

const getRecordTotalRefund = (record) => {
    let total = 0;
    if (record.refundGoodsList?.length) {
        record.refundGoodsList.map(v => {
            if ((record.actualPrice * (v.useExchangeGoodsQuantity)) - (v.storePrice * v.applyRefundNum) > 0) {
                total += Number((record.actualPrice * (v.useExchangeGoodsQuantity) - (v.storePrice * v.applyRefundNum)).toFixed(2))
            } else {
                // total+=0
                total += Number((record.actualPrice * (v.useExchangeGoodsQuantity) - (v.storePrice * v.applyRefundNum)).toFixed(2))
            }
        })
    }
    if (total == 0 && record.soldOutGoodsNum) {
        return (record.soldOutGoodsNum * record.actualPrice).toFixed(2)
    } else {
        return total == 0 && !record.soldOutGoodsNum ? '0.00' : total == 0 && !record.soldOutGoodsNum ? '0.00' : Number((((record.soldOutGoodsNum * record.actualPrice)) + total).toFixed(2))
    }
}

const getTotalRefund = () => {
    let total = 0, selectedRows = goodsList.value.filter((a) => !!a.checked);
    selectedRows?.map(v => {
        total += Number(getRecordTotalRefund(v))
    })
    return Number(total.toFixed(2))
}
const sumKind = () => {
    let total = 0, selectedRows = goodsList.value.filter((a) => !!a.checked);;
    selectedRows.filter((a) => (a.pickUpNum > 0 || a.refundGoodsList?.filter((v) => !!v.applyRefundNum)?.length > 0))?.map((v) => {
        total += v.refundGoodsList?.length;
        if (getPickUpNum(v) > 0) {
            total += 1
        }
    })
    return total
}

const getApplyRefundNum = () => {
    let total = 0, list = [], pickUpNum = 0, selectedRows = goodsList.value.filter((a) => !!a.checked);
    selectedRows?.filter((a) => !!a.refundGoodsList?.length)?.map((v) => {
        pickUpNum += Number(getPickUpNum(v))
        list = list.concat(v.refundGoodsList)
    })
    total = list?.reduce((accumulator, currentValue) => {
        let num = Number(currentValue.applyRefundNum);
        if (!isNaN(num)) {
            return accumulator + num;
        } else {
            return accumulator;
        }
    }, 0) || 0;
    return Number(total) + Number(pickUpNum)
}
const getPickUpWeight = (item) => {
    let pickUpGoodsNum = getPickUpNum(item), goodsWeight = item.goodsWeight * 1000;
    return goodsWeight * pickUpGoodsNum
}

const getExchangeNum = (item) => {
    let total = 0;
    total = item.refundGoodsList?.length && item.refundGoodsList?.reduce((accumulator, currentValue) => {
        let num = Number(currentValue.useExchangeGoodsQuantity);
        if (!isNaN(num)) {
            return accumulator + num;
        } else {
            return accumulator;
        }
    }, 0) || 0;

    return Number(total)
}
const toSelectGds = (rowNo) => {
    uni.navigateTo({
        url: '/pages/BcmViews/modals/storegoods/index?rowNo=' + rowNo + '&storeCode=' + bcmOrder.value.storeCode + '&chnlType=' + bcmOrder.value.chnlType
    })
}

const plusNum = (index, i) => {
    let list = [...goodsList.value], item = list[index];
    item.refundGoodsList[i].applyRefundNum++;
    goodsList.value = list;
}

const minusNum = (index, i) => {
    let list = [...goodsList.value], item = list[index];
    if (item.refundGoodsList[i].applyRefundNum == 1) {
        uni.showModal({
            title: '提示',
            content: '确定删除该换货行吗?',
            success: function (res) {
                if (res.confirm) {
                    item.refundGoodsList.splice(i, 1);
                    goodsList.value = list;
                }
            }
        })
    }
    if (item.refundGoodsList[i].applyRefundNum > 1) {
        item.refundGoodsList[i].applyRefundNum--;
        goodsList.value = list;
    }

}
const minusExchangeNum = (type = 'add') => {
    // console.log(type, 'type', exchangeType.value)
    if (type == 'add') {
        if (exchangeType.value == '0') {
            if (currentItem.value.soldOutGoodsNum) {
                currentItem.value.soldOutGoodsNum--;
            }
        } else {
            if (currentItem.value.isFreshGoods == '1') {
                if (currentItem.value.soldOutGoodsNum > 1) {
                    currentItem.value.soldOutGoodsNum--;
                }
            } else {
                if (currentItem.value.useExchangeGoodsQuantity > 1) {
                    currentItem.value.useExchangeGoodsQuantity--;
                }
            }

        }
    } else {
        if (exchangeGoodsItem.value.useExchangeGoodsQuantity) {
            if (exchangeGoodsItem.value.useExchangeGoodsQuantity >= 1) {
                exchangeGoodsItem.value.useExchangeGoodsQuantity--;
            } else {
                exchangeGoodsItem.value.useExchangeGoodsQuantity = 0
            }
        }
    }
}
const plusExchangeNum = (type = 'add') => {
    let list = [...goodsList.value], item = list[currentItemIndex.value];
    if (type == 'add') {
        if (exchangeType.value == '1') {
            if (currentItem.value.isFreshGoods == '1') {
                if (currentItem.value.soldOutGoodsNum < getPickUpNum(item)) {
                    currentItem.value.soldOutGoodsNum++;
                }
            } else {
                if (currentItem.value.useExchangeGoodsQuantity < getPickUpNum(item)) {
                    currentItem.value.useExchangeGoodsQuantity++;
                }
            }
        } else {
            if (currentItem.value.soldOutGoodsNum < getRestExchangeNum(item)) {
                currentItem.value.soldOutGoodsNum++;
            }
        }
    } else {
        if (exchangeGoodsItem.value.useExchangeGoodsQuantity < item.refundGoodsList[exchangeGoodsIndex.value].useExchangeGoodsQuantity) {
            exchangeGoodsItem.value.useExchangeGoodsQuantity++;
        }
    }
}

const plusExchangeNumNormal = () => {
    exchangeGoodsItem.value.applyRefundNum++;
}

const minusExchangeNumNormal = () => {
    if (exchangeGoodsItem.value.applyRefundNum) {
        exchangeGoodsItem.value.applyRefundNum--
    }
}
const getPickUpNum = (item) => {
    let total = 0;
    total = item?.refundGoodsList?.length && item?.refundGoodsList?.reduce((accumulator, currentValue) => {
        let num = Number(currentValue.useExchangeGoodsQuantity);
        if (!isNaN(num)) {
            return accumulator + num;
        } else {
            return accumulator;
        }
    }, 0) || 0;
    return Number((item?.goodsNum - Number(item?.soldOutGoodsNum) - Number(total)).toFixed(3))
}

const checkboxChange = (index) => {
    let list = [...goodsList.value], item = list[index];
    // $set(item, 'checked', !item.checked)
    item.checked = !item.checked;
    goodsList.value = list;
}

const SelectionChanged = (event) => {
    // console.log(event, 'event')
    if (event.type === 'goodsItem') {
        let list = [...goodsList.value], i = currentItemIndex.value;
        if (i != -1) {
            const { goodsName, goodsBarcode, goodsCode, id, actualPrice, isFreshGoods, weight, code } = event.goodsInfo;
            let goodsItemIndex = list[i].refundGoodsList?.findIndex(f => f?.id == id)
            if (list[i].refundGoodsList?.length) {
                if ((!!goodsItemIndex && goodsItemIndex != -1) || (goodsItemIndex == 0)) {
                    list[i].refundGoodsList[goodsItemIndex].applyRefundNum++;
                    if (isFreshGoods == '1') {
                        list[i].refundGoodsList[goodsItemIndex].applyRefundWeight += weight * 1000;
                    }
                    list[i].refundGoodsList[goodsItemIndex].useExchangeGoodsQuantity += Number(currentItem.value.isFreshGoods == '1' ? currentItem.value.soldOutGoodsNum : currentItem.value.useExchangeGoodsQuantity);
                } else {
                    list[i].refundGoodsList.push({
                        goodsName,
                        goodsBarcode,
                        goodsCode,
                        storePrice: actualPrice,
                        id,
                        code,
                        applyRefundNum: 1,
                        useExchangeGoodsQuantity: Number(currentItem.value.isFreshGoods == '1' ? currentItem.value.soldOutGoodsNum : currentItem.value.useExchangeGoodsQuantity),
                        isFreshGoods,
                        applyRefundWeight: weight * 1000,
                        weight: weight * 1000
                    })
                }

            } else {
                list[i].refundGoodsList = [];
                list[i].refundGoodsList.push({
                    goodsName,
                    storePrice: actualPrice, goodsBarcode, goodsCode,
                    code, id,
                    applyRefundNum: 1,
                    useExchangeGoodsQuantity: Number(currentItem.value.isFreshGoods == '1' ? currentItem.value.soldOutGoodsNum : currentItem.value.useExchangeGoodsQuantity),
                    isFreshGoods,
                    applyRefundWeight: weight * 1000,
                    weight: weight * 1000
                })
            }
            list[i].useExchangeGoodsQuantity += Number(currentItem.value.isFreshGoods == '1' ? currentItem.value.soldOutGoodsNum : currentItem.value.useExchangeGoodsQuantity);
            list[i].checked = true;
            goodsList.value = list;
            closeContactCustPopup()
        }
    }
}
const sumNum = (key) => {
    let selectedRows = goodsList.value.filter((a) => !!a.checked);
    return selectedRows.reduce((accumulator, currentValue) => {
        let num = Number(currentValue[key]);
        if (!isNaN(num)) {
            return accumulator + num;
        } else {
            return accumulator;
        }
    }, 0);
}
const sumRows = (key) => {
    let selectedRows = goodsList.value.filter((a) => !!a.checked);
    return selectedRows.filter(a => a[key] > 0)?.length;
}

const buttonClick = async function (t) {
    const { singleTag } = t;
    let list1 = goodsList.value.filter(a => !!a.checked), list = [...goodsList.value], item = list[currentItemIndex.value], pickGoodsDetailList = [];
    switch (singleTag) {
        case 'confirm':
            if (list1.length == 0) {
                uni.showToast({
                    title: '请选择需要换货的商品',
                    icon: 'none'
                });
                return;
            }
            list1?.map(v => {
                if (v.refundGoodsList?.length) {
                    v.refundGoodsList?.map(f => {
                        pickGoodsDetailList.push({
                            exchangeGoodsBarcode: f.goodsBarcode,
                            exchangeGoodsCode: f.goodsCode,
                            exchangeCode: f.code,
                            exchangeGoodsQuantity: f.applyRefundNum,
                            goodsBarcode: v.goodsBarcode,
                            goodsCode: v.goodsCode,
                            quantity: v.goodsNum,
                            useExchangeGoodsQuantity: f.useExchangeGoodsQuantity,
                            rowNo: v.orderGoodsRow,
                            pickQuantity: getPickUpNum(v)
                        })
                    })
                } else {
                    pickGoodsDetailList.push({
                        goodsBarcode: v.goodsBarcode,
                        goodsCode: v.goodsCode,
                        quantity: v.goodsNum,
                        rowNo: v.orderGoodsRow,
                        pickQuantity: getPickUpNum(v)
                    })
                }

            })
            // console.log(pickGoodsDetailList, 'pickGoodsDetailList')
            let text = pickGoodsDetailList.filter(v => !!v.useExchangeGoodsQuantity).length == 0 ? '确认提交本次缺货操作吗？' : '缺货拣货成功后会产生新的订单，原订单自动取消，您确定要缺货拣货吗？'
            uni.showModal({
                title: '拣货完成确认',
                content: text,
                success: function (res) {
                    if (res.confirm) {
                        confirmExchange(pickGoodsDetailList)
                    }
                }
            })
            break;
        case 'close':
            popup.value.close('bottom');
            break;
        case 'cancel':
            closeContactCustPopup();
            break;
        case 'confirmexchange':
            if (exchangeType.value == '0') {
                if (item.isFreshGoods == '1' && (!Number.isInteger(currentItem.value.applyRefundWeight))) {
                    uni.showToast({
                        icon: 'none',
                        title: "请输入大于或者等于0的整数"
                    })
                    return
                }
                item.soldOutGoodsNum = Number(currentItem.value.soldOutGoodsNum);
                item.checked = true
                goodsList.value = list;
                closeContactCustPopup()
            } else {
                if (!!currentItem.value.useExchangeGoodsQuantity) {
                    toSelectGds(currentItem.value.orderGoodsRow);
                } else {
                    uni.showToast({
                        icon: 'none',
                        title: "请输入大于0的整数"
                    })
                    return
                }
            }
            break;
        case 'confirmexchangeEdit':
            if (exchangeGoodsItem.value.useExchangeGoodsQuantity == 0 || exchangeGoodsItem.value.applyRefundNum == 0) {
                uni.showModal({
                    title: '提示',
                    content: '确定删除该换货行吗?',
                    success: function (res) {
                        if (res.confirm) {
                            item.refundGoodsList.splice(exchangeGoodsIndex.value, 1);
                            goodsList.value = list;
                            closeEditExchangeInfoPopup()
                        }
                    }
                })
            } else {
                item.refundGoodsList[exchangeGoodsIndex.value] = {
                    ...item.refundGoodsList[exchangeGoodsIndex.value],
                    ...exchangeGoodsItem.value,
                    applyRefundWeight: exchangeGoodsItem.value.applyRefundNum * exchangeGoodsItem.value.weight
                }
                goodsList.value = list;
                closeEditExchangeInfoPopup()
            }
            break;
        case 'editCancel':
            closeEditExchangeInfoPopup()
            break;
        case 'submit':
            // plus.device.dial(bcmOrder.value.consigneePhone, true);
            makePhoneCall(bcmOrder.value.consigneePhone)
            break;
    }
}
const close = function () {
    popup.value.close();
}

const confirmExchange = async function (pickGoodsDetailList) {
    service.enjoyShowLoading('正在处理...');
    let params = {
        orderId: bcmOrder.value.orderId,
        pickOperateType: '6',
        storeCode: bcmOrder.value.storeCode,
        chnlType: bcmOrder.value.chnlType,
        pickGoodsDetailList
    }

    await bcmRequest(bcmUrl.orderApi, '订单表', 'pickingComplete', params);
    service.enjoyHideLoading();
    uni.showToast({
        title: '缺货拣货操作成功！',
        icon: 'none'
    });
    AddSelectDataToPrePage({
        type: 'exchange',
        result: true
    })
    setTimeout(() => {
        uni.navigateBack({
            delta: 1
        });
        uni.$emit('REFRESH_ORDER_DETAIL_DATA');
        uni.$emit('REFRESH_ORDER_SEARCH_DATA')
    }, 1000)
}

const AddSelectDataToPrePage = (param) => {
    //通知上一界面刷新
    if (param) {
        try {
            let pages = getCurrentPages(); //获取所有页面栈实例列表
            let prevPage = pages[pages.length - 2]; //上一页页面实例
            prevPage.$vm.$.exposed.SelectionChanged(param); //执行函数也是同理
            // uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
            //     delta: 1
            // });
        } catch (e) {
            console.log(JSON.stringify(e));
            //TODO handle the exception
        }
    }
}

const openContactCustPop = (item, index) => {
    currentItem.value = JSON.parse(JSON.stringify(item));
    currentItemIndex.value = index;
    currentItem.value.soldOutGoodsNum = getRestExchangeNum(goodsList.value[index]);
    currentItem.value.soldOutWeight = getRestExchangeNum(goodsList.value[index]) * (item.goodsWeight / item.goodsNum) * 1000;
    currentItem.value.applyRefundWeight = 0;
    exchangeType.value = '0';
    addExchangeInfoPopup.value.open('bottom');
}
const closeContactCustPopup = function () {
    addExchangeInfoPopup.value.close();
}
const closeEditExchangeInfoPopup = function () {
    editExchangeInfoPopup.value.close();
}
const openEditExchangeInfoPopup = function () {
    editExchangeInfoPopup.value.open('bottom');
}

// 获取订单详情信息
const billQuery = async (BillId) => {
    service.enjoyShowLoading('正在加载...');
    const req = {
        BillId,
        extras: {
            queryAfsOrder: "0",
            queryAfsApproved: "0"
        }
    };
    const result = await bcmRequest(bcmUrl.orderApi, '订单表', 'EnjoyBillQuery', req);
    service.enjoyHideLoading();
    if (!!result.ds.bcmOrder) {
        bcmOrder.value = result.ds.bcmOrder;
        result.ds.bcmOrderGoodsList?.map(v => {
            goodsList.value.push({
                ...v,
                returnGoodsList: [],
                soldOutGoodsNum: 0,
                useExchangeGoodsQuantity: 0
            })
        })
    } else {
        bcmOrder.value = null;
        goodsList.value = [];
        uni.showToast({
            duration: 3500,
            icon: 'none',
            title: '未查询到数据',
        });
    }
}

defineExpose({
    SelectionChanged
})

</script>
<style lang="scss" scoped>
@import "@/static/font/enjoyicon/iconfont.css";
@import "../common/common.css";

uni-checkbox {
    ::v-deep .uni-checkbox-input {
        transform: scale(.6);
    }
}

.footer {
    display: flex;
    flex-direction: column;
    flex: 1;
    background: #f5f7fa;
}

.align-center {
    align-items: center;
}

.bottom {
    display: flex;
    justify-content: center;
    height: 86rpx;
    height: 86rpx;
    // background: $uni-bg-color;
}

.bottom-1 {
    display: flex;
    justify-content: center;
    flex: 0 0 auto;
    height: 86rpx;
    padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
    background: $uni-bg-color;
}

//list
.goods-item {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    padding: 5rpx 10rpx 5rpx 0;
    border-bottom: 1rpx solid #e1e1e1;
}

.goods-info {
    align-items: baseline;
    // display: flex;
    flex: 1;
    color: #000;
}

.goods-name {
    // margin-bottom: 2px;
    font-size: 32rpx;
    line-height: 35rpx;
}

.goods-price {
    // color: #626262;
    font-size: 32rpx;
    text-align: right;
}

.goods-quantity {
    color: #626262;
    font-size: 32rpx;
}

.popup-content {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 50vh;
    padding: 0;
    background-color: #fff;

    .popup-title {
        display: flex;
        align-items: center;
        box-sizing: border-box;
        width: 100%;
        height: 100rpx;
        padding-right: 36rpx;
        padding-left: 32rpx;
        font-size: 33rpx;
        line-height: 100rpx;
        border-bottom: 1px solid #f1f1f1;
    }

    textarea {
        box-sizing: border-box;
        width: 100%;
        height: 80px;
        padding: 5px;
        margin: 5px 0;
        border: 1px solid #ccc;
        border-radius: 5px;
    }
}
</style>
